<?php

namespace App\Utils;

use Illuminate\Support\Collection;

class FunctionUtil
{
  /**
   * json_encode设置
   * @param $obj
   * @return false|string
   */
  public static function jsonEncode($obj): bool|string
  {
    return json_encode($obj, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  }


  /**
   * 返回数据格式化, 对象转化数组格式
   * @param array|object $data 需要格式化的返回数据
   * @return array 已格式化的数据
   */
  public static function formatResult(array|object $data): array
  {
    $result = [];
    is_object($data) && $data = (new Collection($data))->toArray();
    if (is_array($data)) {
      foreach ($data as $key => $value) {
        is_object($value) && $value = (new Collection($value))->toArray();
        if (is_array($value)) {
          $value = empty($value) ? [] : self::formatResult($value);
        } else if (empty($value) && $value !== 0 && $value !== "0") {
          $value = '';
        }
        $result[$key] = $value;
      }
    }
    return $result;
  }

  /**
   * 十进制数转换成36进制
   *
   * @param integer $num
   * @return string
   */
  public static function numberTo36(int $num): string
  {
    $to = 36;
    $dict = 'b4loq7cu0ztd2fhvr8wx1ay9i5pgs3me6njk';
    $ret = '';
    do {
      $ret = $dict[bcmod($num, $to)] . $ret;
      $num = bcdiv($num, $to);
    } while ($num > 0);
    return $ret;
  }


}
